package com.siwei.mes.service.experiment.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.siwei.mes.common.query.PageQuery;
import com.siwei.mes.entity.ShxhSynchronizedata;
import com.siwei.mes.entity.UploadLaboratoryEntity;
import com.siwei.mes.entity.erp.Itemorder;
import com.siwei.mes.entity.experiment.Experiment;
import com.siwei.mes.entity.experiment.ExperimentItemorder;
import com.siwei.mes.enums.TestProjectEnum;
import com.siwei.mes.mapper.ShxhSynchronizedataMapper;
import com.siwei.mes.mapper.experiment.ExperimentItemorderMapper;
import com.siwei.mes.mapper.experiment.ExperimentMapper;
import com.siwei.mes.service.experiment.ExperimentItemorderService;
import com.siwei.mes.sync.config.SyncProcessorService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringEscapeUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

import static com.siwei.mes.common.exception.handler.MessageHandler.assertTrue;

/**
 * 试验台账与小票关系(ExperimentItemorder)表服务实现类
 *
 * @author linzi
 * @since 2023-12-19 22:36:28
 */
@Slf4j
@Service
public class ExperimentItemorderServiceImpl implements ExperimentItemorderService {
    @Resource
    private ExperimentItemorderMapper experimentItemorderMapper;
    @Resource
    private ExperimentMapper experimentMapper;
    @Resource
    private SyncProcessorService syncProcessorService;
    @Resource
    private ShxhSynchronizedataMapper shxhSynchronizedataMapper;

    @Override
    public Long create(ExperimentItemorder entity) {
        experimentItemorderMapper.insertSelective(entity);
        return entity.getId();
    }

    @Override
    public void update(ExperimentItemorder entity) {
        ExperimentItemorder experimentItemorder = experimentItemorderMapper.selectByPrimaryKey(entity.getId());
        assertTrue(experimentItemorder == null, "试验台账与小票关系信息不存在");
        experimentItemorderMapper.updateByPrimaryKeySelective(entity);
    }

    @Override
    public void delete(Long id) {
        ExperimentItemorder experimentItemorder = experimentItemorderMapper.selectByPrimaryKey(id);
        assertTrue(experimentItemorder == null, "试验台账与小票关系信息不存在");
        experimentItemorderMapper.deleteByPrimaryKey(id);
    }

    @Override
    public PageInfo<ExperimentItemorder> getPage(PageQuery<ExperimentItemorder, ExperimentItemorder> query) {
        ExperimentItemorder searchParam = query.getParams();
        return PageHelper.startPage(query.getPageNum(), query.getPageSize())
                .doSelectPageInfo(() -> experimentItemorderMapper.getList(searchParam));
    }

    @Override
    public ExperimentItemorder loadById(Long id) {
        return experimentItemorderMapper.loadById(id);
    }

    @Override
    public List<ExperimentItemorder> getAll(ExperimentItemorder entity) {
        return experimentItemorderMapper.getList(entity);
    }

    @Override
    public List<Itemorder> selectByExperimentId(Long experimentId, Integer frwdh) {
        List<Itemorder> itemorderList = experimentItemorderMapper.selectByExperimentIdFrwdh(experimentId, frwdh);
        for (Itemorder entity : itemorderList) {
            if (entity == null) {
                continue;
            }
            try {
                if (StringUtils.isNotBlank(entity.getExtrainfo())) {
                    String entityExtrainfo = StringEscapeUtils.unescapeJava(entity.getExtrainfo());
                    JSONObject jsonObject = JSON.parseObject(entityExtrainfo);
                    entity.setFhy(jsonObject.getString("fhy"));
                }
            } catch (Exception e) {
                entity.setFhy("");
            }
        }
        return itemorderList;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteByExperimentIdAndItemorderId(Long experimentId, Integer itemorderId) {
        log.info("开始删除混凝土试验委托和小票的关联，试验委托id：【{}】，小票id：【{}】", experimentId, itemorderId);

        Experiment experiment = experimentMapper.loadById(experimentId);
        assertTrue(experiment == null, "试验台账信息不存在");

        experimentItemorderMapper.delete(new ExperimentItemorder().setExperimentId(experimentId).setItemorderId(itemorderId));

        /**重新计算试验委托数量*/
        List<Itemorder> itemorderList = experimentItemorderMapper.selectByExperimentId(experimentId);
        double behalfNumber = itemorderList.stream().map(Itemorder::getScquantity).reduce((float) 0, Float::sum);
        Experiment updateInfo = new Experiment();
        updateInfo.setId(experimentId);
        updateInfo.setBehalfNumber(behalfNumber);
        updateInfo.init(false);
        experimentMapper.updateByPrimaryKeySelective(updateInfo);


        /**这里判断是否已经上传到协会，如果没有上传到协会就不推送*/
        ShxhSynchronizedata shxhSynchronizedata = shxhSynchronizedataMapper.selectByExperimentIdOne(experimentId);
        if (shxhSynchronizedata != null && shxhSynchronizedata.getSampleId() != null) {
            log.info("删除混凝土试验委托和小票关系，推送到协会处理代表数量。");

            /**推送到协会*/
            List<String> experimentIdList = new ArrayList<>();
            experimentIdList.add(experimentId.toString());

            List<Experiment> hntExperiment = new ArrayList<>();

            if (experiment.getEntrustExperiment().contains(TestProjectEnum.CONCRETE_PARAM_KYQD.getName())) {
                hntExperiment = experimentMapper.getHntKyExperiment();
            } else if (experiment.getEntrustExperiment().equals(TestProjectEnum.CONCRETE_PARAM_KSDJ.getName())) {
                hntExperiment = experimentMapper.getHntKsExperiment();
            }
            syncProcessorService.submitRequest(new UploadLaboratoryEntity().setExperimentId(experimentIdList).setUploadState(0).setHntExperiment(hntExperiment));
        }
    }
}
